<template>
  <el-dialog :title="showTitle" :visible="showDialog" width="50%" @close="btnCancel">
    <el-form ref="form" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" placeholder="1-50个字符"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="form.description" placeholder="1-300个字符" type="textarea" :rows="3"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
    <el-button @click="btnCancel">取 消</el-button>
    <el-button type="primary" @click="btnOk">确 定</el-button>
  </span>
  </el-dialog>
</template>

<script>

  import {addRole, getRoleDetail, updateRole} from "@/api/setting";

  export default {
    name: "add-role",
    props: {
      showDialog: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        form: {
          name: '', // 角色名称
          description: '' // 角色描述
        },
        rules: {
          name: [
            {required: true, message: '请输入角色名称', trigger: 'blur'},
            {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
          ]

        }
      }

    },

    methods: {
      btnOk() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            if (this.form.id) {
              await updateRole(this.form)
            } else {
              await addRole(this.form)
            }
            this.$emit('update:showDialog', false)
            this.$emit('addRole')
          }

        })
      },
      btnCancel() {
        this.form = {
          name: '', // 角色名称
          description: '' // 角色描述
        }
        this.$emit('update:showDialog', false)
        this.$refs.form.resetFields()
      },
      async getRoleDetail(id) {
        this.form = await getRoleDetail(id)
      }
    },
    computed: {
      showTitle() {
        return this.form.id ? '编辑角色' : '新增角色'
      }
    }

  }
</script>

<style scoped>

</style>
